﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.DAL.Common;
using DHQGHN.PM0.Models.Admin;
using DHQGHN.PM0.Controllers;
using DHQGHN.Common;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.MVC.Controllers;

namespace DHQGHN.PM0.Controllers.Admin
{
    public class MaritalStatusController : BaseController
    {
        MaritalStatusBO maritalStatusBO;
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(MaritalStatusController));

        public ActionResult Index()
        {
            try
            {
                ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
                ViewBag.ActiveMenus[13] = "active";
                ViewBag.ActiveMenus[227] = "active";
                MaritalStatusModel msModel = new MaritalStatusModel
                {
                    Name = null,
                    Code = null,
                    Deleted = 2
                };
                var model = search(msModel, 0, string.Empty);
                return View("~/Views/MaritalStatus/MaritalStatus.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        public ActionResult actionSearch(MaritalStatusModel msModel = null, int pageIndex = 0, string sort = "Code", string sortDir = "ASC", string currentId = null)
        {
            try
            {
                if (msModel == null) msModel = new MaritalStatusModel();
                if (string.IsNullOrEmpty(currentId)) currentId = string.Empty;

                var model = search(msModel, pageIndex, currentId);
                return PartialView("~/Views/MaritalStatus/_MaritalStatusList.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        public ActionResult actionPrepareCreateOrUpdate(string maritalStatusId)
        {
            try
            {
                MaritalStatusModel marital = null;
                if (!String.IsNullOrEmpty(maritalStatusId))
                {
                    maritalStatusBO = new MaritalStatusBO();
                    marital = new MaritalStatusModel(maritalStatusBO.GetMaritalStatusById(maritalStatusId));
                }
                if (marital == null)
                {
                    marital = new MaritalStatusModel()
                    {
                        Name = string.Empty,
                        Code = string.Empty,
                        Marital_Status_Id = string.Empty,
                        Descriptions = string.Empty
                    };
                }

                if (Request.IsAjaxRequest())
                {
                    return PartialView("~/Views/MaritalStatus/_MaritalStatusModel.cshtml", marital);
                }
                //RedirectToAction("ManageUsers", "Admin");
                return View(marital);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult actionCreateOrUpdateMarital(MaritalStatusModel model)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    maritalStatusBO = new MaritalStatusBO();
                    bool result = maritalStatusBO.createOrUpdate(model.toDALModel());
                    if (result)
                    {
                        LogStream.Write<MaritalStatusModel>(GetCurrentUserName(),
                           CommonData.AppName,
                           GetFunction(),
                           Resources.Localization.ActionSaveUpdateCaption + " - actionCreateOrUpdateMarital", model);

                        return Json(JsonResponse.Json200(Resources.Localization.Confirm_Save_Success));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500(Resources.Localization.Confirm_Save_Error));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        public ActionResult actionActive(string maritalStatusId)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    maritalStatusBO = new MaritalStatusBO();
                    bool result = true;
                    MaritalStatusModel msModel = new MaritalStatusModel(maritalStatusBO.GetMaritalStatusById(maritalStatusId));
                    msModel.Deleted = 0;
                    maritalStatusBO.createOrUpdate(msModel.toDALModel());
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            CommonData.GetListId(new string[] { maritalStatusId }),
                            Resources.Localization.ActionActiveCaption + " - actionActive");

                        return Json(JsonResponse.Json200(Resources.Localization.Confirm_Save_Success));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500(Resources.Localization.Confirm_Save_Error));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        public ActionResult actionDelete(string[] ids)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    maritalStatusBO = new MaritalStatusBO();
                    bool result = true;
                    result = maritalStatusBO.deleteMarital(ids);

                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            CommonData.GetListId(ids),
                            Resources.Localization.ActionDeleteCaption + " - actionDelete");
                        return Json(JsonResponse.Json200(Resources.Localization.Confirm_Delete_Success));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500(Resources.Localization.Confirm_Save_Error));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        public JsonResult CheckExistMaritalCode(string Code, string Marital_Status_Id)
        {
            try
            {
                if(string.IsNullOrEmpty(Code))
                    return Json(Resources.Localization.MaritalStatusCodeExist);

                MaritalStatusModel msModel = new MaritalStatusModel()
                {
                    Code = Code.Trim()
                };
                if (!String.IsNullOrEmpty(Marital_Status_Id))
                {
                    msModel.Marital_Status_Id = Marital_Status_Id;
                }
                bool check = checkMaritalExist(msModel);
                if (check)
                {
                    return Json(Resources.Localization.MaritalStatusCodeExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        public JsonResult CheckExistMaritalName(string Name, string Marital_Status_Id)
        {
            try
            {
                if(string.IsNullOrEmpty(Name))
                    return Json(Resources.Localization.MaritalStatusNameExist);
 
                MaritalStatusModel msModel = new MaritalStatusModel()
                {
                    Name = Name.Trim()
                };
                if (!String.IsNullOrEmpty(Marital_Status_Id))
                {
                    msModel.Marital_Status_Id = Marital_Status_Id;
                }
                bool check = checkMaritalExist(msModel);
                if (check)
                {
                    return Json(Resources.Localization.MaritalStatusNameExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private bool checkMaritalExist(MaritalStatusModel model)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    maritalStatusBO = new MaritalStatusBO();
                    return maritalStatusBO.checkMaritalExist(model.Marital_Status_Id, model.Code, model.Name);
                }
                return false;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private object search(MaritalStatusModel msModel, int pageIndex, string currentId)
        {
            try
            {
                maritalStatusBO = new MaritalStatusBO();
                var DALModel = maritalStatusBO.GetDynamicListPaging(msModel.toDALModel(), PageSize, pageIndex);
                var model = new DataPage<MaritalStatusModel>();
                var lstItem = DALModel.Data;
                foreach (DHQGHN.DAL.Models.Admin.MaritalStatusModel marital in lstItem)
                {
                    model.Data.Add(new MaritalStatusModel(marital));
                }

                MaritalStatusModel maritalStatusModel = null;
                if (!String.IsNullOrEmpty(currentId))
                {
                    maritalStatusModel = model.Data.Find(m => m.Marital_Status_Id == currentId);
                    model.CustomData = maritalStatusModel;
                }
                else
                {
                    model.CustomData = msModel;
                }
                if (model.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "MaritalStatus",
                        CurrentPage = pageIndex,
                        InputSearchId = string.Empty,
                        TagetReLoadId = "ms-list",

                    };
                    pagNative.TotalRows = model.Data[0].RecordCount;
                    pagNative.CurrentRow = model.Data.Count;
                    ViewBag.Pagination = pagNative;
                }
                return model;
            }
            catch
            {
                throw;
            }
        }

        private string GetFunction()
        {
            return "Danh mục tình trạng hôn nhân";
        }
    }
}